using System;
using System.Linq;
using System.Web.Mvc;
using Kollektiv.DataModel;
using Kollektiv.Web.Mvc;
using Kollektiv.Validation;
using Kollektiv.Tool;

namespace Kollektiv.Controller
{
	public class User : Session
	{
        [ControllerAction]
        public ActionResult Home()
        {
            return null;
        }

		[ControllerAction]
		public bool Create ([EmailRPV]string email, [NameRPV]string firstName, [NameRPV]string lastName, string languageISO)
		{
			BaseDataService.BeginTransaction ();
			try {
				string randomPassword = RandomPassword.Generate ();
				Language language = BaseDataService.GetRepository<LanguageRepository> ().All
					.Where (l => l.ISO == languageISO).FirstOrDefault ();
				
				if (language == null)
					language = DefaultLanguage;
				
				DataModel.User user = BaseDataService.GetRepository<UserRepository> ()
						.Create (email, firstName, lastName, randomPassword, language);
				
				this.SendPassword (user, randomPassword);
				
				BaseDataService.CommitTransaction ();
				return true;
			} catch (Exception ex) {
				BaseDataService.RollbackTransaction ();
				throw(ex);
			}
		}
		
		[ControllerAction]
		public Guid Login ([EmailRPV]string email, string password)
		{
			UserRepository userRepository = BaseDataService.GetRepository<UserRepository> ();
			SessionRepository sessionRepository = BaseDataService.GetRepository<SessionRepository> ();
			DataModel.User user = userRepository.All
				.Where (x => x.Email == email).FirstOrDefault ();
			
			if (user != null && user.VerifyPassword (password)) {
				return sessionRepository.Create (user).UID;
			} else {
				throw(new ArgumentException ("email/password is wrong"));
			}
		}
		
		[ControllerAction]
		public void Logout ()
		{
			if (this.UserSession != null) {
				SessionRepository sessionRepository = BaseDataService.GetRepository<SessionRepository> ();
				sessionRepository.Delete (this.UserSession);
			}
		}
		
		private void SendPassword (DataModel.User user, string password)
		{
			EmailContent emailContent = BaseDataService.GetRepository<EmailContentRepository> ().All
				.Where (ec => ec.Type == "Kollektiv.UserController.SendPassword" && ec.Language == user.Language)
				.FirstOrDefault ();
			
			if (emailContent == null)
				emailContent = BaseDataService.GetRepository<EmailContentRepository> ().All
					.Where (ec => ec.Type == "Kollektiv.UserController.SendPassword" && ec.Language == DefaultLanguage)
					.FirstOrDefault ();
			
			string text = emailContent.Text
				.Replace ("$(FirstName)", user.FirstName)
				.Replace ("$(LastName)", user.LastName)
				.Replace ("$(Password)", password);
			
			EmailService.Send (user.Email, emailContent.Title, text);
		}
	}
}

